package com.qipay.api.auth.controller;

import com.qipay.auth.service.AuthService;
import com.qipay.scalar.type.ApiStatusEnum;
import com.qipay.security.jwt.service.JWTTokenService;
import com.qipay.utils.ResultUtils;
import com.qipay.utils.XmlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Value("${jwt.header}")
    private String tokenHeader;

    @Value("${jwt.expiration}")
    private int expirateion;

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JWTTokenService jwtTokenService;
    @Autowired
    private AuthService authService;

    @RequestMapping(value = "/access-token", method = RequestMethod.GET,
            produces = {"application/xml;charset=UTF-8"})
    public @ResponseBody String createAuthenticationToken(
            @RequestParam(name = "appid") @NotNull String appid,
            @RequestParam(name = "secretid") @NotNull String secretid) throws IOException {

        String token = null;

        token = authService.getToken(appid, secretid);

        Assert.notNull(token,
                ResultUtils.buildErrorMsg(ApiStatusEnum.UNAUTHENTICATION, "密钥或AppId错误"));

        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(appid, secretid);
        final Authentication authentication = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        Map<String, Object> result=new HashMap<>();
        result.put("token", token);
        result.put("token_expir_second", expirateion);
        return XmlUtils.toString(result, "xml");
    }

}
